<script setup lang="ts">
import { computed, ref } from 'vue'
import { searchGoodsAPI, tagListAPI } from '@/services/category'
import { onShow, onLoad, onReady } from '@dcloudio/uni-app'
import type { GoodsResult } from '@/types/goods'
import { useMemberStore } from '@/stores'
import {
  unlimitedQrcodeAPI,
  saveInvitationRecordAPI,
  getMemberPointInfoAPI,
  getActivitiesInfoAPI,
  generateUrllinkAPI,
} from '@/services/points'
import type { InvitationInfo } from '@/types/points'
const { getUserInfo } = useMemberStore()
const systemInfo = uni.getSystemInfoSync()
const { safeAreaInsets } = systemInfo

const qrcode = ref('' as any)
const invitationsInfo = ref({} as InvitationInfo)
const activityInfo = ref({} as any)

const generateCodeHandler = async () => {
  const res = await unlimitedQrcodeAPI({
    scene: 'abc_123',
  })
  qrcode.value = res.data
}

// 页面右上角分享功能生效
const onShareAppMessage = (res: any) => {
  if (res.from === 'button') {
    // 来自页面内分享按钮
    console.log(res.target)
  }
  return {
    title: '邀请有礼',
    path: '/pagesMember/points/invitations?inviterId=' + getUserInfo()?.id, // 邀请人id
    imageUrl: '@/static/images/stars.png',
  }
}

const onShareTimeline = (res: any) => {
  return {
    title: '自定义分享到朋友圈标题',
    query: 'inviterId=' + getUserInfo()?.id, // 分享的参数，格式与web页面的query相同
    imageUrl: '@/static/images/stars.png', // 同样支持本地文件路径、代码包文件路径或网络图片路径
  }
}

onLoad((e: any) => {
  const inviterId = e.inviterId

  // 保存邀请人ID（仅当参数存在时）
  if (inviterId) {
    uni.setStorageSync('inviterId', inviterId)
    // 请先登录
    if (!getUserInfo()?.id) {
      uni.showToast({ title: '请先登录', icon: 'none' })
      uni.navigateTo({ url: '/pages/login/login' })
    }
  }
})

// ✅ 关键：在 onShow 中处理邀请逻辑
onShow(() => {
  // 活动详情
  getActivitiesInfoAPI('邀请有礼').then((res) => {
    activityInfo.value = res.data

    const inviterId = uni.getStorageSync('inviterId')
    const userInfo = getUserInfo()

    if (inviterId && userInfo?.id) {
      // 保存邀请记录
      saveInvitationRecordAPI({
        activityId: activityInfo.value.id,
        inviterId,
        inviteeId: userInfo.id,
        inviterPoints: activityInfo.value.inviterPoints,
        inviteePoints: activityInfo.value.inviteePoints,
      }).then((res) => {
        uni.showToast({ title: res.data, icon: 'none' })
        uni.removeStorageSync('inviterId')
        invitationsInfoRequest(activityInfo.value.id)
      })
    } else {
      invitationsInfoRequest(activityInfo.value.id)
    }
  })
})
const invitationsInfoRequest = async (activityId: number) => {
  const res = await getMemberPointInfoAPI({
    userId: getUserInfo()?.id,
    activityId,
  })
  invitationsInfo.value = res.data
}

const percent = computed(() => {
  return ((invitationsInfo.value.personCount || 0) / 10) * 100
})

const copyLink = async () => {
  const res = await generateUrllinkAPI({
    page: 'pagesMember/points/invitations',
    query: `inviterId=${getUserInfo()?.id}`,
  })

  uni.setClipboardData({
    data: res.data,
    success: () => {
      uni.showToast({ title: '链接已复制', icon: 'none' })
    },
    fail: () => {
      uni.showToast({ title: '复制失败', icon: 'error' })
    },
  })
}

const handleShare = (type: string) => {
  switch (type) {
    case 'wechat':
      // 这里不需要额外操作，因为使用了open-type="share"
      break
    case 'timeline':
      uni.showToast({
        title: '请点击右上角「转发」按钮 → 分享到朋友圈',
        icon: 'none',
        duration: 3000,
      })
      break
    case 'link':
      copyLink()
      break
  }
}
</script>

<template>
  <view class="invitations-page" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
    <scroll-view scroll-y :show-scrollbar="false" enable-back-to-top>
      <view class="banner">
        <image :src="activityInfo.imageUrl" mode="scaleToFill"></image>
      </view>
      <view class="wrap">
        <view class="wrap-item">
          <view class="wrap-item-title">
            <view class="left">
              <text class="label">已邀请人数:</text>
              <text class="val">{{ invitationsInfo.personCount }}</text>
            </view>
            <view class="right">
              <text class="label">累计获得积分:</text>
              <text class="val">{{ invitationsInfo.points }}</text>
            </view>
          </view>
          <view class="wrap-item-content">
            <progress
              class="progress"
              :percent="percent"
              :active="true"
              stroke-width="16rpx"
              activeColor="#EF4444"
              border-radius="8rpx"
              backgroundColor="#E5E7EB"
            />
            <view class="con">
              <text class="label">邀请任务:</text>
              <text class="val">{{ invitationsInfo.personCount }}/10</text>
            </view>
          </view>
        </view>
      </view>
      <view class="activity-list">
        <view class="activity-item">
          <view class="activity-item-title">
            <text class="iconfont icon-hangyehuodong"></text>
            <text class="text">{{ activityInfo.inviterTitle }}</text>
          </view>
          <view class="activity-item-con">
            <rich-text :nodes="activityInfo.inviterDescription"></rich-text>
          </view>
        </view>
        <view class="activity-item">
          <view class="activity-item-title">
            <text class="iconfont icon-maiyizengyi"></text>
            <text class="text">{{ activityInfo.inviteeTitle }}</text>
          </view>
          <view class="activity-item-con">
            <rich-text :nodes="activityInfo.inviteeDescription"></rich-text>
          </view>
        </view>
      </view>
      <!-- <view>
        <view @tap="generateCodeHandler()">生成邀请码</view>
        <image class="qrcode" :src="qrcode" mode="scaleToFill" />
      </view> -->
      <view class="method-list">
        <view class="method-title">邀请方式</view>
        <view class="method-icons">
          <!-- 微信好友分享 -->
          <button
            class="icons-item"
            open-type="share"
            @click="handleShare('wechat')"
            plain
            hover-class="none"
          >
            <text class="iconfont icon-weixin"></text>
            <text>微信</text>
          </button>

          <!-- 朋友圈分享 -->
          <button class="icons-item" @click="handleShare('timeline')" plain hover-class="none">
            <text class="iconfont icon-fenxiang3"></text>
            <text>朋友圈</text>
          </button>

          <!-- 链接分享 -->
          <button class="icons-item" @click="handleShare('link')" plain hover-class="none">
            <text class="iconfont icon-lianjie_o"></text>
            <text>链接</text>
          </button>
          <!-- <view class="icons-item">
            <text class="iconfont icon-share"></text>
            <text>QQ</text>
          </view> -->
        </view>
      </view>

      <view class="rule-list">
        <view class="rule-title">活动规则</view>
        <view class="rule-item">
          <rich-text :nodes="activityInfo.description"></rich-text>
        </view>
        <view class="tip">已经有{{ activityInfo.countTotal }}人参与活动</view>
      </view>
    </scroll-view>
  </view>
</template>

<style lang="scss">
@import '@/styles/variables.scss';
.qrcode {
  width: 200rpx;
  height: 200rpx;
}
page {
  height: 100%;
  overflow: hidden;
  background-color: #fff;
}
.invitations-page {
  height: 100%;
  display: flex;
  flex-direction: column;

  .banner {
    width: 780rpx;
    height: 360rpx;
    background: linear-gradient(to right, #dc2626 100%, #ef4444 100%);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-size: $color;
  }

  .wrap {
    // 假设性的父容器样式
    height: 152rpx;
    width: 100%;
    position: relative;

    .wrap-item {
      position: absolute;
      bottom: 0;
      left: 28rpx;
      right: 28rpx;
      padding: 32rpx;
      background-color: white;
      border-radius: 24rpx;
      box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
      display: flex;
      flex-direction: column;

      .wrap-item-title {
        display: flex;
        justify-content: space-between;
        margin-bottom: 24rpx;

        .left,
        .right {
          display: flex;
          align-items: center;

          .label {
            font-size: $font-size;
            color: #000;
            margin-right: 10rpx;
            font-weight: $font-regular-weight;
          }

          .val {
            font-size: $font-size;
            color: #ef4444;
            font-weight: $font-regular-weight;
          }
        }
      }

      .wrap-item-content {
        .progress {
          width: 100%;
          height: 16rpx; // 注意：在实际使用中，确保正确处理 rpx 单位
          border-radius: 8rpx;
          background-color: #ccc;
        }

        .con {
          display: flex;
          justify-content: flex-end;
          margin-top: 10rpx;
          margin-left: auto;

          .label,
          .val {
            font-size: $font-size;
            color: #555;
            font-weight: $font-regular-weight;
          }
          .label {
            margin-right: 10rpx;
          }
        }
      }
    }
  }

  .activity-list {
    margin-top: 28rpx;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 0 28rpx;
    gap: $small-padding; // 列之间的间距

    .activity-item {
      flex: 1;
      font-size: $font-size;
      font-weight: $font-regular-weight;
      background-color: white;
      border-radius: 24rpx;
      box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
      padding: 28rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .activity-item-title {
        display: flex;
        align-items: center;
        margin-bottom: 20rpx;

        .iconfont {
          font-size: 30rpx;
          color: #ef4444; // 与你之前的渐变色呼应
          margin-right: 16rpx;
          border-radius: 50%;
          background-color: #fee2e2;
          width: 40rpx;
          height: 40rpx;
          display: flex;
          justify-content: center;
          align-items: center;
        }

        .text {
          font-size: $font-size;
          font-weight: $font-regular-weight;
          color: #000;
        }
      }

      .activity-item-con {
        font-size: 24rpx;
        color: #555;
        line-height: 1.6;

        .weight {
          color: #ef4444; // 与你之前的渐变色呼应
        }
      }
    }
  }

  .method-list {
    padding: 28rpx;
    margin-top: 28rpx;

    .method-title {
      font-size: 34rpx;
      font-weight: 600;
      color: #000;
      margin-bottom: 28rpx;
    }

    .method-txt-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 24rpx 30rpx;
      border-radius: 12rpx;
      margin-bottom: 30rpx;
      font-size: 28rpx;

      background: linear-gradient(to right, #facc15 100%, #fde047 100%);

      .text {
        flex: 1;
        color: #991b1b;
        font-size: 28rpx;
        font-weight: $font-SemiBold-weight;
      }

      .copy-btn {
        // “复制”文字样式
        background-color: #fff;
        height: 72rpx;
        padding: 0 28rpx;
        border-radius: 36rpx;
        display: flex;
        align-items: center;
        .iconfont {
          font-size: 40rpx;
          color: #ef4444;
          margin-right: 8rpx;
        }
        font-size: 28rpx;
        color: #000;
      }
    }

    .method-icons {
      display: flex;
      justify-content: space-around;
      align-items: center;

      .icons-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        font-size: 28rpx;
        color: #000;
        justify-content: center;
        border: 0;
        // 各图标颜色可单独定义（示例）
        .iconfont {
          font-size: 60rpx;
          color: #4b5563;
          width: 80rpx;
          height: 80rpx;
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: center;
          border-radius: 50%;
          background: #fff;
          box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
          margin-bottom: 20rpx;
        }
        &:nth-child(1) {
          .iconfont {
            color: #07c160;
          }
        } // 微信
        &:nth-child(2) {
          .iconfont {
            color: #07c160;
          }
        }
        &:nth-child(3) {
          .iconfont {
            color: #fa5151;
          }
        } // 分享
        &:nth-child(4) {
          .iconfont {
            color: #5677fc;
          }
        } // 链接
      }
    }
  }

  .rule-list {
    padding: 28rpx;
    margin-top: 28rpx;

    .rule-title {
      font-size: 34rpx;
      font-weight: 600;
      color: #000;
      margin-bottom: 28rpx;
    }

    .rule-item {
      font-size: 28rpx;
      color: #374151;
      line-height: 1.7;
      padding: 28rpx;
      // background-color: #f3f4f6;
      background-color: #fdf2f2;
      border: 1rpx solid #fecaca;
      border-radius: 12rpx;
      white-space: pre-line; // 保留换行和空格，使文本更易读
      text-indent: 0; // 避免首行缩进

      // 如果你想让每条规则单独成段，建议用 v-for 和结构化数据
      // 但现在是纯文本，我们通过样式优化可读性
    }
    .tip {
      color: #6b7280;
      font-size: 24rpx;
      font-weight: $font-regular-weight;
      text-align: center;
      margin: 20rpx 0;
    }
  }
}
</style>
